package com.jstyle.jclife.fragment;

import android.content.Context;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.HeartTipsActivity;
import com.jstyle.jclife.adapter.HistoryShowAdapter;
import com.jstyle.jclife.adapter.SleepDetailAdapter;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.SleepData;
import com.jstyle.jclife.model.SleepDetail;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.ActivityHistoryCircleProgress;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SleepDayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SleepDayFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.iv_activity_history_left)
    ImageView ivActivityHistoryLeft;

    @BindView(R.id.iv_activity_history_right)
    ImageView ivActivityHistoryRight;
    @BindView(R.id.RecyclerView_data_day)
    RecyclerView RecyclerViewDataDay;
    @BindView(R.id.LineChartView_sleep_status)
    LineChartView LineChartViewSleepStatus;
    @BindView(R.id.LineChartView_sleepHeartChart)
    LineChartView LineChartViewSleepHeartChart;
    @BindView(R.id.RecyclerView_sleepDetail)
    RecyclerView RecyclerViewSleepDetail;
    Unbinder unbinder;
    float showRight = 0;

    //睡眠数据标题
    @BindArray(R.array.sleep_detailContent_array)
    String[] detailTitle_array;
    //睡眠数据范围
    @BindArray(R.array.sleep_detailLimit_array)
    String[] detailLimit_array;
    @BindView(R.id.bt_nohr)
    Button btNohr;
    @BindView(R.id.bt_nosleep)
    Button btNosleep;
    @BindView(R.id.sleep_rl)
    RelativeLayout sleepRl;
    @BindView(R.id.NestedScrollView)
    android.support.v4.widget.NestedScrollView NestedScrollView;
    //睡眠数据内容
    private float[] contentArray = new float[6];
    @BindView(R.id.tv_data_day_deepSleepTime)
    TextView tvDataDayDeepSleepTime;
    @BindView(R.id.tv_data_day_lightSleepTime)
    TextView tvDataDayLightSleepTime;
    @BindView(R.id.tv_data_day_awakeTime)
    TextView tvDataDayAwakeTime;

    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.sleep_circleView)
    ActivityHistoryCircleProgress sleepCircleView;
    @BindView(R.id.bt_avgSleepHR)
    Button btAvgSleepHR;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private static final String TAG = "SleepDayFragment";
    private String queryDate;

    private List<String> listContent = new ArrayList<>();
    private HistoryShowAdapter historyShowAdapter;

    private SleepDetailAdapter sleepDetailAdapter;
    private List<SleepDetail> sleepDetailArray = new ArrayList<>();
    private int avgHR = 0;
    private Typeface mFace;

    public SleepDayFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SleepDayFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SleepDayFragment newInstance(String param1, String param2) {
        SleepDayFragment fragment = new SleepDayFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sleep_day, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        initData();
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void addSleepDetail() {
        sleepDetailArray.clear();
        for (int i = 0; i < detailTitle_array.length; i++) {
            SleepDetail sleepDetail = new SleepDetail();
            sleepDetail.setTitle(detailTitle_array[i]);
            sleepDetail.setContent(contentArray[i]);
            sleepDetail.setLimit(detailLimit_array[i]);
            sleepDetailArray.add(sleepDetail);
        }
    }

    @OnClick({R.id.bt_sleepHeartTips, R.id.iv_activity_history_left, R.id.iv_activity_history_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sleepHeartTips:
                startActivity(HeartTipsActivity.class, HeartTipsActivity.TipsType, HeartTipsActivity.TipsType_SleepHeart);
                break;
            case R.id.iv_activity_history_right:
                queryDate = DateUtil.getTomorrowDateString(queryDate);
                initData();
                break;
            case R.id.iv_activity_history_left:
                queryDate = DateUtil.getYesterdayDateString(queryDate);
                initData();
                break;
        }
    }

    private void initData() {
        btSleepWeekDate.setText(DateUtil.getShowDaySleep(getActivity(), queryDate));
        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        ivActivityHistoryRight.setEnabled(!queryDate.equals(nowDate));
        String lastDate = DateUtil.getTomorrowDateString(queryDate);
        List<SleepData> sleepDataList = SleepDataDaoManager.queryData(queryDate, lastDate);
        List<HeartData> heartDataList = HeartDataDaoManager.queryData(queryDate, lastDate);
        int[] fiveSleepData = new int[288];//288*5分钟
        for (int i = 0; i < fiveSleepData.length; i++) {
            fiveSleepData[i] = -1;//睡眠数据0为有效数据
        }

        for (SleepData sleepData : sleepDataList) {
            String time = sleepData.getTime();
            String data = sleepData.getDateString();
            int startCount = DateUtil.get5MIndex(time, queryDate + " 12:00:00");
         //   Log.i(TAG, "initData: " + time + " " + data + " " + startCount);
            if (startCount >= 288) break;
            fiveSleepData[startCount] = Integer.valueOf(data) == 0 ? (int) (1 + Math.random() * 7) : Integer.valueOf(data);
        }
        List<Integer> listSleep = new ArrayList<>();
        for (int i = 0; i < fiveSleepData.length; i++) {
            int value = fiveSleepData[i];
            if (value != -1) {
                for (int j = 0; j < 5; j++) {
                    listSleep.add(i * 5 + j);
                }
            }
        }
        int firstCount=0;
        int offsetCount=1;
        for(int i=0;i<heartDataList.size();i++){
            String time = heartDataList.get(i).getTime();
            int startCount = DateUtil.get1MIndex(time, queryDate + " 12:00:00");
            if (listSleep.contains(startCount)){
                if(firstCount==0){
                    firstCount=startCount;
                }else {
                    if(offsetCount==1){
                        offsetCount=startCount-firstCount;
                        Log.i(TAG, "initData: "+offsetCount);
                        break;
                    }
                }
            }
        }
        if(offsetCount==0)offsetCount=1;
        int[] heartDataArray = new int[1440/offsetCount];//1分钟一个点。一天1440
//        int lastCount=listSleep.get(listSleep.size()-1);
//        int firstSleepCount=listSleep.get(0);
//
//
//        int length = fiveSleepData.length;
        float showLeft = -1;
        float showRight = 0;

        List<Integer> sleepTime = getSleepTime(fiveSleepData);
        if (sleepTime.size() != 0) {
            showLeft = sleepTime.get(0);
            showRight = sleepTime.get(sleepTime.size() - 1);
        }
        for (HeartData heartData : heartDataList) {
            String time = heartData.getTime();
            int data = heartData.getHeart();
            int startCount = DateUtil.getMIndex(time, queryDate + " 12:00:00",offsetCount);

            if (startCount >= 1440/offsetCount) break;
            if (isInSleep(sleepTime,startCount*offsetCount)){
                heartDataArray[startCount] = data;
            }

        }
        initHeartChartView(heartDataArray, showLeft,showRight,offsetCount);
        initSleepChartView(fiveSleepData, sleepTime);
    }

    private boolean isInSleep( List<Integer> sleepTime,int count){
        boolean isInSleep=false;
        int sleepCount=sleepTime.size()/2;
        for(int i=0;i<sleepCount;i++){
            int start=sleepTime.get(i*2)*5;
            int end=sleepTime.get(i*2+1)*5;

            if(count>=start&&count<=end){
                isInSleep=true;
                break;
            }
        }
        return isInSleep;
    }
    private List<Integer> getSleepTime(int[] fiveSleepData) {
        List<Integer> list = new ArrayList<>();
        int goBed = -1;
        int upBed = 0;
        int offCount = 0;
        for (int i = 0; i < fiveSleepData.length; i++) {
            int data = fiveSleepData[i];
            if (data != -1) {
                offCount = 0;
                if (goBed == -1) {
                    list.add(i);
                    goBed = i;
                }

            } else {
                offCount++;
                if (offCount == 6 && goBed != -1) {//30分钟离床
                    list.add(i - 5);
                    offCount = 0;
                    goBed = -1;
                }
            }
            if(i==fiveSleepData.length-1&&goBed!=-1){
                list.add(i);
            }
        }
        return list;
    }

    private void initHeartChartView(int[] heartDataArray, float showLeft,float showRight,int offset) {
        int totalHR = 0;
        int count = 0;
        float maxDayHr=0;
        float minDayHr=300;
        for (int value : heartDataArray) {
            if (value != 0) {
                totalHR += value;
                count++;
                maxDayHr = Math.max(maxDayHr, value);
                minDayHr = Math.min(minDayHr, value);
            }
        }
        avgHR = totalHR == 0 ? 0 : totalHR / count;
        btNohr.setVisibility(totalHR == 0 ? View.VISIBLE : View.GONE);
        LineChartViewSleepHeartChart.setVisibility(totalHR == 0 ? View.GONE : View.VISIBLE);

        btAvgSleepHR.setText(String.format(getString(R.string.avg_sleep_heart),avgHR));
        float top=0;
        if(maxDayHr%10==0){
            top=maxDayHr;
        }else{
            top=(((int)maxDayHr/10)+1)*10;
        }
        ChartDataUtil.initDataSleepChartView(LineChartViewSleepHeartChart,
                -1, top+10, heartDataArray.length, 40, (showRight + 2) * (5f/offset), (showLeft - 2) * (5f/offset));

        LineChartViewSleepHeartChart.setLineChartData(ChartDataUtil.getSleepHeartDayChart(getActivity(), heartDataArray,mFace,offset,top));

    }


    private void init() {
         mFace = Typeface.createFromAsset(getActivity().getAssets(),"Brandon_reg.otf");

        sleepDetailAdapter = new SleepDetailAdapter(sleepDetailArray);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewSleepDetail.setLayoutManager(linearLayoutManager);
        RecyclerViewSleepDetail.setAdapter(sleepDetailAdapter);

        String today = TextUtils.isEmpty(mParam1)?DateUtil.getDefaultFormatTime(new Date()):mParam1;

        queryDate = DateUtil.getYesterdayDateString(today);//第一次查询昨天睡觉数据

        FlexboxLayoutManager layoutManager2 = new FlexboxLayoutManager(getActivity());
        listContent.add(getString(R.string.avg_sleep_hr));
        listContent.add(getString(R.string.deep_sleep_time));
        listContent.add(getString(R.string.light_sleep_time));
        historyShowAdapter = new HistoryShowAdapter(listContent);
        RecyclerViewDataDay.setAdapter(historyShowAdapter);
        RecyclerViewDataDay.setLayoutManager(layoutManager2);
    }

    private void initSleepChartView(int[] stepData, List<Integer> sleepTime) {
        float sleepGoal = SharedPreferenceUtils.getFloat(SharedPreferenceUtils.KEY_Sleep_goal, 480);
        int[] sleepLevel = new int[3];
        for (float value : stepData) {
            if (value != -1) sleepLevel[ResolveData.getSleepLevel((int) value)]++;
        }
        float deep = sleepLevel[0];
        float light = sleepLevel[1];
        float awake = sleepLevel[2];
        float total = deep + light + awake;
        int duration = 0;
        if (sleepTime.size() >= 2) {
            int count = sleepTime.size() / 2;

            for (int i = 0; i < count; i++) {
                duration += sleepTime.get(i * 2 + 1) - sleepTime.get(i * 2);
            }

        }
        String totalTime = DateUtil.getPointSleepTime(getActivity(), (int) (duration * 5));
        String deepTime = DateUtil.getPointSleepTime(getActivity(), (int) (deep * 5));
        sleepCircleView.startAnimSleep(totalTime, total * 5 / sleepGoal);
        List<String> list = new ArrayList<>();
        list.add(String.valueOf(avgHR));
        list.add(deepTime);
        list.add(DateUtil.getPointSleepTime(getActivity(), (int) (light * 5)));
        historyShowAdapter.setStepData(list);
        float showLeft = 0;
        float showRight = 0;
        if (sleepTime.size() != 0) {
            showLeft = sleepTime.get(0);
            showRight = sleepTime.get(sleepTime.size() - 1);
        }
        btNosleep.setVisibility(sleepTime.size() == 0 ? View.VISIBLE : View.GONE);
        LineChartViewSleepStatus.setVisibility(sleepTime.size() == 0 ? View.GONE : View.VISIBLE);
        sleepRl.setVisibility(sleepTime.size() == 0 ? View.INVISIBLE : View.VISIBLE);
        ChartDataUtil.initDataSleepChartView(LineChartViewSleepStatus,
                -1, 80, stepData.length, 0, showRight + 10, showLeft - 10);

        LineChartViewSleepStatus.setLineChartData(ChartDataUtil.getSleepDayChart(getActivity(), stepData, sleepTime,mFace));
        float EfficiencyPercent = total == 0 ? 0 : (deep + light) / total;
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(1);
        double dsp = getSleepPercent(total, deep);
        double lsp = getSleepPercent(total, light);
        double asp = total == 0 ? 0 : getAwakePercent(dsp, lsp);
        Log.i(TAG, "initSleepChartView: " + asp);
        String deepSleepPercent = nf.format(dsp);
        String lightSleepPercent = nf.format(lsp);
        String awakeSleepPercent = nf.format(asp);
        try {
            double a = nf.parse(deepSleepPercent).doubleValue() +
                    nf.parse(lightSleepPercent).doubleValue();
            awakeSleepPercent = nf.format(total == 0 ? 0 : 1 - a);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tvDataDayAwakeTime.setText(awakeSleepPercent);
        tvDataDayDeepSleepTime.setText(deepSleepPercent);
        tvDataDayLightSleepTime.setText(lightSleepPercent);
        contentArray[1] = total * 5;
        contentArray[2] = deep * 5;
        contentArray[3] = light * 5;
        contentArray[4] = EfficiencyPercent;
        contentArray[5] = avgHR;
        addSleepDetail();
        sleepDetailAdapter.setData(sleepDetailArray);
    }

    private double getAwakePercent(double dsp, double lsp) {
        Log.i(TAG, "getAwakePercent: ");
        int d = (int) Math.floor(dsp * 1000);
        int l = (int) Math.floor(lsp * 1000);
        return (1000 - d - l) / 1000f;
    }

    private double getSleepPercent(float total, float item) {
        return total == 0 ? 0 : item / total;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void shoot() {
        super.shoot();
        ScreenUtils.shareFile(getActivity(), NestedScrollView);
    }
}
